package com.zhuifeng.smart.daoimpl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.zhuifeng.smart.dao.WebsDao;
import com.zhuifeng.smart.model.Webs;
import com.zhuifeng.smart.util.JdbcUtil;

public class WebsDaoImpl implements WebsDao {
	private static QueryRunner runner = new QueryRunner(
			JdbcUtil.getDataSource());

	@Override
	public List<Webs> getWebsList(String websort) {
		String sql = "select * from webs where websort = ?";
		try {
			return runner.query(sql, new BeanListHandler<Webs>(Webs.class),
					websort);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean addWebs(Webs webs) {
		String sql = "INSERT INTO `smart`.`webs` (`webname`, `website`, `websort`, `webliveness`) VALUES (?,?,?,?)";
		try {
			return runner.update(
					sql,
					new Object[] { webs.getWebname(), webs.getWebsite(),
							webs.getWebsort(), webs.getWebliveness() }) > 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean deleteWebs(String websId) {
		String sql = "DELETE FROM `smart`.`webs` WHERE `_id`=?";
		try {
			return runner.update(sql, websId) > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean updataWebs(Webs webs) {
		String sql = "UPDATE `smart`.`webs` SET `webname`=?, `website`=?, `websort`=?, `webliveness`=? WHERE `_id`=?";
		try {
			return runner.update(
					sql,
					new Object[] { webs.getWebname(), webs.getWebsite(),
							webs.getWebsort(), webs.getWebliveness(),
							webs.get_id() }) > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public int getNewsId(Webs webs) {
		String sql = "select _id from webs where `webname`=? and `website`=? and `websort`=? and `webliveness`=?";
		Webs w = null;
		try {
			w = runner.query(
					sql,
					new BeanHandler<Webs>(Webs.class),
					new Object[] { webs.getWebname(), webs.getWebsite(),
							webs.getWebsort(), webs.getWebliveness() });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return w.get_id();
	}

}
